package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mr_Su
 * @version v1.0
 * @date 2022/7/10 21:07
 * @desciption
 */
@Service
public class ApUserSearchServiceImpl {


    @Autowired
    private MongoTemplate mongoTemplate;
    @Async
    public void saveUserSearch(String keyword, Integer userId, String equipmentId){
        // 记录搜索历史
        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setEquipmentId(equipmentId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());


        // 判断当前用户查询的关键词是否已经有记录
        Query query = new Query();
        Criteria criteria = Criteria.where("keyword").is(keyword);
        if (userId == 0){// 未登录
            criteria.and("equipmentId").is(equipmentId);
        }else {
            criteria.and("userId").is(userId);
        }
        long count = mongoTemplate.count(query, ApUserSearch.class);
        if (count == 0){
            mongoTemplate.save(apUserSearch);
        }

    }

    public ResponseResult load(ApArticleSearchDto dto) {
        User user = UserThreadLocalUtil.get();
        // 判断当前用户查询的关键词是否已经有记录
        Query query = new Query();
        if (user.getUserId() == 0){// 未登录
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }else {
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.limit(5);
        List<ApUserSearch> userSearchList = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(userSearchList);
    }

    public ResponseResult delete(ApArticleSearchDto dto) {
        List<ApUserSearch> hisList = dto.getHisList();

        List<String> stringList = hisList.stream().map(ApUserSearch::getId).collect(Collectors.toList());
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").in(stringList));
        mongoTemplate.remove(query, ApUserSearch.class);
        return ResponseResult.okResult();
    }
}
